package com.alog.javaee.day41;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/2/17 15:59
 * @Description:
 */
@WebServlet("/checkCodeServlet3")
public class CheckCodeServlet2 extends HttpServlet {
    String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 50;

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //背景
        Graphics graphics = bi.getGraphics();
        graphics.setColor(Color.PINK);
        graphics.fillRect(0,0, 100, 50);

        //边框
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0,0, width-1, height-1);

        //随机码
//        graphics.drawString("A",20, 25);
//        graphics.drawString("B",40, 25);
//        graphics.drawString("C",60, 25);
//        graphics.drawString("D",80, 25);
        StringBuilder builder = new StringBuilder();
        for(int i = 1 ; i <= 4; i++){
            int index = random.nextInt(str.length());
            String ch = str.charAt(index) + "";
            builder.append(ch);
            graphics.drawString(ch,20 * i, height / 2);
        }
        request.getSession().setAttribute("sessionCheckCode", builder.toString());
        //干扰线
        graphics.setColor(Color.GREEN);
        //graphics.drawLine(1,1, 30, 30);
        for(int i = 0; i < 10; i++){
            graphics.drawLine(random.nextInt(width),random.nextInt(height),
                    random.nextInt(width),random.nextInt(height));
        }


        ImageIO.write(bi, "jpg", response.getOutputStream());

    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
